package com.forlove.app.qselect.friend.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.network.ICallBack;
import com.forlove.app.common.network.OkhttpManager;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.ParseHelper;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.common.widget.recyview.ViewHolder;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.answer.entity.InviteShortLinkEntity;
import com.forlove.app.qselect.answer.widght.InviteFriendDialog;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.friend.entity.SearchFriendEntity;
import com.forlove.app.qselect.friend.presenter.MineNewFriendPresenter;
import com.forlove.app.qselect.friend.ui.SearchUserInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.forlove.app.qselect.friend.ui.MineNewFriendFragment.add_new_contacts_friend;

/**
 * 好友界面未注册通讯录好友界面
 * Created by yjl on 2017/10/14.
 */

public class UnRegisterContactcsAdapter extends BaseRecyclerAdapter<MineFriendEntity> {
    private MineNewFriendPresenter presenter;
    private String from;
    private Context context;
    private UserEntity userEntity;
    private String commonShareUrl;
    private String shareUrl;
    private InviteFriendDialog inviteFriendDialog;

    public UnRegisterContactcsAdapter(Context context, int itemView, List<MineFriendEntity> mDatas, MineNewFriendPresenter presenter) {
        super(context, itemView, mDatas);
        this.presenter = presenter;
        this.context = context;
        userEntity = UserManager.getUesrInfo(mContext);
        try {
            commonShareUrl = ServerManager.getServerUrl() + "/invtepage?username=" + URLEncoder.encode(userEntity.userName, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void convertView(ViewHolder holder, final MineFriendEntity entity, final int position) {
        if (StringUtils.isNotEmpty(entity.getContactsName())) {
            holder.setText(R.id.text_friend__name, entity.getContactsName());
        }
        presenter.loadImageView(mContext, holder.getView(R.id.view_friend_photo), entity.img, R.mipmap.image_mine_friend_avatar);
        if (entity.commonFriends > 0) {
            holder.setVisible(R.id.text_friend_from, false);
            holder.setText(R.id.text_qyq_name, entity.commonFriends + "个共同好友");
        } else if (entity.charm > 0) {
            holder.setVisible(R.id.text_friend_from, false);
            holder.setText(R.id.text_qyq_name, "魅力值:" + entity.charm);
        } else {
            holder.setVisible(R.id.text_friend_from, false);
            holder.setText(R.id.text_qyq_name, entity.getAvaliableMobile());
        }
        TextView text_friend_states = holder.getView(R.id.text_friend_states);
        if (entity.status == add_new_contacts_friend) {
            text_friend_states.setBackgroundColor(Color.parseColor("#ffffff"));
            text_friend_states.setTextColor(mContext.getResources().getColor(R.color.str_color_gray));
            text_friend_states.setText("等待验证");
            text_friend_states.setOnClickListener(null);
        } else if (entity.isfriend && !TextUtils.isEmpty(entity.realname)) {
            //是好友，并注册
            text_friend_states.setBackgroundColor(Color.parseColor("#ffffff"));
            text_friend_states.setTextColor(mContext.getResources().getColor(R.color.str_color_gray));
            text_friend_states.setText("已添加");
            text_friend_states.setOnClickListener(null);
        } else if (!entity.isfriend && !TextUtils.isEmpty(entity.realname)){
            //未注册完成，未填写真实姓名的用户情况会显示邀请
//                || entity.status == NewsFriendsStatus.UNADDED.getCode()) {
            // 不是好友，但是是注册用户
            text_friend_states.setBackground(mContext.getResources().getDrawable(R.drawable.bt_invite_selector));
            text_friend_states.setTextColor(mContext.getResources().getColor(R.color.white));
            text_friend_states.setText("添加");
            text_friend_states.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转申请加好友界面
                    SearchFriendEntity searchFriendEntity = new SearchFriendEntity();
                    searchFriendEntity.friendEntity = entity;
                    searchFriendEntity.note_times = entity.charm;
                    searchFriendEntity.isFriend = false;
                    Intent intent = new Intent(mContext, SearchUserInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putSerializable("friendinfo", searchFriendEntity);
                    bundle.putString("mobile", entity.getAvaliableMobile());
                    intent.putExtras(bundle);
                    if (mContext instanceof Activity) {
                        ((Activity) mContext).startActivityForResult(intent, add_new_contacts_friend);
                    } else {
                        mContext.startActivity(intent);
                    }
                }
            });
        } else if (!entity.isfriend && TextUtils.isEmpty(entity.realname)) {
            //不是好友并且未注册
            text_friend_states.setBackground(mContext.getResources().getDrawable(R.drawable.bt_invite_selector));
            text_friend_states.setTextColor(mContext.getResources().getColor(R.color.white));
            text_friend_states.setText("邀请");

            text_friend_states.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareUrl = commonShareUrl;
                    if (!TextUtils.isEmpty(entity.getAvaliableName())) {
                        try {
                            shareUrl = commonShareUrl + "&invt=" + URLEncoder.encode(entity.getAvaliableName(), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    getShortLink(shareUrl);
                }
            });
        }

    }

    public void clearData() {
        if (inviteFriendDialog != null) {
            inviteFriendDialog.dismiss();
            inviteFriendDialog.clearRecycle();
            inviteFriendDialog = null;
        }
        presenter = null;
    }

    public void getShortLink(String url) {
        try {
            if (inviteFriendDialog == null) {
                inviteFriendDialog = new InviteFriendDialog(mContext, shareUrl, null, null);
            }
            Map param = new HashMap();
            param.put("url_long", url);
            param.put("source", "445798234");
            OkhttpManager.getInstance().loadDataByPost(ServerManager.URL_SHORT_LINK, param, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, String result) {
                    LogUtil.e("yjl", "onSuccess short link：" + result);
                    try {
                        result = result.replaceAll(" ", "");
                        result = result.replaceAll("\\n", "");
                        List<InviteShortLinkEntity> inviteShortLinkEntity = ParseHelper.getModelList(result, "urls", InviteShortLinkEntity.class);
                        if (inviteShortLinkEntity != null && inviteShortLinkEntity.size() > 0) {
                            shareUrl = inviteShortLinkEntity.get(0).url_short;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    inviteFriendDialog.setShareUrl(shareUrl);
                    ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            inviteFriendDialog.show();
                        }
                    });

                }

                @Override
                public void onFail(int statusCode, String result) {
                    LogUtil.e("yjl", "onFail short link：" + result);
                    inviteFriendDialog.setShareUrl(shareUrl);
                    ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            inviteFriendDialog.show();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {

        if (mDatas == null || mDatas.size() == 0) {
            return 1;
        } else {
            if (mDatas.size() > 30) {
                return 30;
            }
            return mDatas.size();
        }
    }

}
